<template>
  <div class="merchant-account-detail">
    <el-tabs v-model="activeTab">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="120px"
          class="basic-form"
        >
          <el-form-item label="账户名称" prop="name">
            <el-input v-model="basicForm.name" placeholder="请输入账户名称" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="basicForm.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="basicForm.email" placeholder="请输入电子邮箱" />
          </el-form-item>
          <el-form-item label="账户状态" prop="status">
            <el-tag :type="getStatusType(basicForm.status)">
              {{ getStatusText(basicForm.status) }}
            </el-tag>
          </el-form-item>
          <el-form-item label="注册时间">
            {{ basicForm.createTime }}
          </el-form-item>
          <el-form-item label="最后登录">
            {{ basicForm.lastLoginTime }}
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpdateBasic">保存修改</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 数据统计 -->
      <el-tab-pane label="数据统计" name="statistics">
        <div class="statistics-cards">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>今日订单数</span>
                  </div>
                </template>
                <div class="card-value">{{ statistics.todayOrders }}</div>
                <div class="card-trend">
                  较昨日
                  <span :class="statistics.orderTrend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(statistics.orderTrend) }}%
                  </span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>今日销售额</span>
                  </div>
                </template>
                <div class="card-value">¥{{ statistics.todaySales }}</div>
                <div class="card-trend">
                  较昨日
                  <span :class="statistics.salesTrend >= 0 ? 'up' : 'down'">
                    {{ Math.abs(statistics.salesTrend) }}%
                  </span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>累计订单数</span>
                  </div>
                </template>
                <div class="card-value">{{ statistics.totalOrders }}</div>
                <div class="card-trend">总订单数</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>累计销售额</span>
                  </div>
                </template>
                <div class="card-value">¥{{ statistics.totalSales }}</div>
                <div class="card-trend">总销售额</div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <div class="statistics-charts">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>销售趋势</span>
                    <el-radio-group v-model="salesChartType" size="small">
                      <el-radio-button label="week">本周</el-radio-button>
                      <el-radio-button label="month">本月</el-radio-button>
                      <el-radio-button label="year">本年</el-radio-button>
                    </el-radio-group>
                  </div>
                </template>
                <div class="chart-container">
                  <v-chart :option="salesChartOption" autoresize />
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>订单分布</span>
                  </div>
                </template>
                <div class="chart-container">
                  <v-chart :option="orderChartOption" autoresize />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 安全中心 -->
      <el-tab-pane label="安全中心" name="security">
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>账户安全</span>
            </div>
          </template>
          <div class="security-items">
            <div class="security-item">
              <div class="item-info">
                <div class="item-title">登录密码</div>
                <div class="item-desc">定期修改密码可以保护账号安全</div>
              </div>
              <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
            </div>
            <div class="security-item">
              <div class="item-info">
                <div class="item-title">手机绑定</div>
                <div class="item-desc">已绑定：{{ basicForm.phone }}</div>
              </div>
              <el-button type="primary" @click="handleChangePhone">修改手机</el-button>
            </div>
            <div class="security-item">
              <div class="item-info">
                <div class="item-title">邮箱绑定</div>
                <div class="item-desc">已绑定：{{ basicForm.email }}</div>
              </div>
              <el-button type="primary" @click="handleChangeEmail">修改邮箱</el-button>
            </div>
            <div class="security-item">
              <div class="item-info">
                <div class="item-title">登录设备管理</div>
                <div class="item-desc">查看并管理已登录的设备</div>
              </div>
              <el-button type="primary" @click="handleManageDevices">管理设备</el-button>
            </div>
          </div>
        </el-card>

        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>登录记录</span>
            </div>
          </template>
          <el-table :data="loginRecords" border style="width: 100%">
            <el-table-column prop="loginTime" label="登录时间" />
            <el-table-column prop="device" label="登录设备" />
            <el-table-column prop="ip" label="登录IP" />
            <el-table-column prop="location" label="登录地点" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                  {{ row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <!-- 审核流程 -->
      <el-tab-pane label="审核流程" name="audit">
        <el-card class="audit-card">
          <template #header>
            <div class="card-header">
              <span>审核状态</span>
              <el-tag :type="getAuditStatusType(auditInfo.status)">
                {{ getAuditStatusText(auditInfo.status) }}
              </el-tag>
            </div>
          </template>
          <el-steps :active="getAuditStep(auditInfo.status)" finish-status="success">
            <el-step title="提交申请" :description="auditInfo.submitTime" />
            <el-step title="初审" :description="auditInfo.firstAuditTime" />
            <el-step title="复审" :description="auditInfo.secondAuditTime" />
            <el-step title="终审" :description="auditInfo.finalAuditTime" />
          </el-steps>
        </el-card>

        <el-card class="audit-card">
          <template #header>
            <div class="card-header">
              <span>审核记录</span>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in auditRecords"
              :key="index"
              :timestamp="record.time"
              :type="getAuditRecordType(record.status)"
            >
              {{ record.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-tab-pane>

      <!-- 通知管理 -->
      <el-tab-pane label="通知管理" name="notification">
        <el-card class="notification-card">
          <template #header>
            <div class="card-header">
              <span>通知设置</span>
            </div>
          </template>
          <el-form
            ref="notificationFormRef"
            :model="notificationForm"
            label-width="120px"
          >
            <el-form-item label="订单通知">
              <el-switch
                v-model="notificationForm.orderNotification"
                active-text="开启"
                inactive-text="关闭"
              />
            </el-form-item>
            <el-form-item label="系统通知">
              <el-switch
                v-model="notificationForm.systemNotification"
                active-text="开启"
                inactive-text="关闭"
              />
            </el-form-item>
            <el-form-item label="营销通知">
              <el-switch
                v-model="notificationForm.marketingNotification"
                active-text="开启"
                inactive-text="关闭"
              />
            </el-form-item>
            <el-form-item label="通知方式">
              <el-checkbox-group v-model="notificationForm.notificationMethods">
                <el-checkbox label="sms">短信</el-checkbox>
                <el-checkbox label="email">邮件</el-checkbox>
                <el-checkbox label="internal">站内信</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateNotification">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="notification-card">
          <template #header>
            <div class="card-header">
              <span>通知记录</span>
            </div>
          </template>
          <el-table :data="notificationRecords" border style="width: 100%">
            <el-table-column prop="time" label="通知时间" />
            <el-table-column prop="type" label="通知类型">
              <template #default="{ row }">
                <el-tag>{{ getNotificationTypeText(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="通知标题" />
            <el-table-column prop="content" label="通知内容" show-overflow-tooltip />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="row.status === 'read' ? 'success' : 'info'">
                  {{ row.status === 'read' ? '已读' : '未读' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  link
                  @click="handleViewNotification(row)"
                >
                  查看
                </el-button>
                <el-button
                  v-if="row.status === 'unread'"
                  type="success"
                  link
                  @click="handleMarkAsRead(row)"
                >
                  标记已读
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              v-model:current-page="notificationPage"
              v-model:page-size="notificationPageSize"
              :total="notificationTotal"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleNotificationSizeChange"
              @current-change="handleNotificationCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="notificationDetailVisible"
      title="通知详情"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="通知类型">
          {{ getNotificationTypeText(currentNotification.type) }}
        </el-descriptions-item>
        <el-descriptions-item label="通知时间">
          {{ currentNotification.time }}
        </el-descriptions-item>
        <el-descriptions-item label="通知标题">
          {{ currentNotification.title }}
        </el-descriptions-item>
        <el-descriptions-item label="通知内容">
          <div class="notification-content">{{ currentNotification.content }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { ElMessage } from 'element-plus'
import {
  getMerchantAccountDetail,
  updateMerchantAccount,
  getMerchantAccountStatistics,
  getMerchantAccountSecurity,
  updateMerchantAccountSecurity,
  getMerchantAccountNotification,
  updateMerchantAccountNotification,
  getMerchantAccountAuditHistory,
  getMerchantAccountLoginHistory
} from '@/api/merchant'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

// 当前激活的标签页
const activeTab = ref('basic')

// 基本信息表单
const basicFormRef = ref(null)
const basicForm = reactive({
  name: '',
  phone: '',
  email: '',
  status: '',
  createTime: '',
  lastLoginTime: ''
})

// 统计数据
const statistics = reactive({
  todayOrders: 0,
  orderTrend: 0,
  todaySales: 0,
  salesTrend: 0,
  totalOrders: 0,
  totalSales: 0
})

// 图表数据
const salesChartType = ref('week')
const salesChartOption = reactive({
  title: {
    text: '销售趋势'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '销售额',
      type: 'line',
      data: [],
      smooth: true
    }
  ]
})

const orderChartOption = reactive({
  title: {
    text: '订单分布'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '订单状态',
      type: 'pie',
      radius: '50%',
      data: []
    }
  ]
})

// 安全中心数据
const loginRecords = ref([])

// 审核流程数据
const auditInfo = reactive({
  status: '',
  submitTime: '',
  firstAuditTime: '',
  secondAuditTime: '',
  finalAuditTime: ''
})
const auditRecords = ref([])

// 通知管理数据
const notificationFormRef = ref(null)
const notificationForm = reactive({
  orderNotification: true,
  systemNotification: true,
  marketingNotification: false,
  notificationMethods: ['sms', 'email', 'internal']
})
const notificationRecords = ref([])
const notificationPage = ref(1)
const notificationPageSize = ref(10)
const notificationTotal = ref(0)

// 修改密码对话框
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 通知详情对话框
const notificationDetailVisible = ref(false)
const currentNotification = ref({})

// 表单验证规则
const basicRules = {
  name: [{ required: true, message: '请输入账户名称', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取账户详情
const getAccountDetail = async () => {
  try {
    const { data } = await getMerchantAccountDetail()
    Object.assign(basicForm, data)
  } catch (error) {
    console.error('获取账户详情失败:', error)
    ElMessage.error('获取账户详情失败')
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantAccountStatistics()
    Object.assign(statistics, data)
    
    // 更新销售趋势图表
    salesChartOption.xAxis.data = data.salesTrend.map(item => item.date)
    salesChartOption.series[0].data = data.salesTrend.map(item => item.value)
    
    // 更新订单分布图表
    orderChartOption.series[0].data = data.orderDistribution
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取登录记录
const getLoginHistory = async () => {
  try {
    const { data } = await getMerchantAccountLoginHistory()
    loginRecords.value = data
  } catch (error) {
    console.error('获取登录记录失败:', error)
    ElMessage.error('获取登录记录失败')
  }
}

// 获取审核记录
const getAuditHistory = async () => {
  try {
    const { data } = await getMerchantAccountAuditHistory()
    Object.assign(auditInfo, data.info)
    auditRecords.value = data.records
  } catch (error) {
    console.error('获取审核记录失败:', error)
    ElMessage.error('获取审核记录失败')
  }
}

// 获取通知设置
const getNotificationSettings = async () => {
  try {
    const { data } = await getMerchantAccountNotification()
    Object.assign(notificationForm, data)
  } catch (error) {
    console.error('获取通知设置失败:', error)
    ElMessage.error('获取通知设置失败')
  }
}

// 更新基本信息
const handleUpdateBasic = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    await updateMerchantAccount(basicForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('更新基本信息失败:', error)
  }
}

// 修改密码
const handleChangePassword = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    await updateMerchantAccountSecurity({
      type: 'password',
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
  } catch (error) {
    console.error('修改密码失败:', error)
  }
}

// 更新通知设置
const handleUpdateNotification = async () => {
  try {
    await updateMerchantAccountNotification(notificationForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('更新通知设置失败:', error)
  }
}

// 查看通知详情
const handleViewNotification = (row) => {
  currentNotification.value = row
  notificationDetailVisible.value = true
}

// 标记通知已读
const handleMarkAsRead = async (row) => {
  try {
    await updateMerchantAccountNotification({
      type: 'mark-read',
      notificationId: row.id
    })
    ElMessage.success('标记成功')
    getNotificationRecords()
  } catch (error) {
    console.error('标记通知已读失败:', error)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    active: 'success',
    inactive: 'info',
    pending: 'warning',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    active: '正常',
    inactive: '禁用',
    pending: '待审核',
    rejected: '已拒绝'
  }
  return map[status] || status
}

// 获取审核状态类型
const getAuditStatusType = (status) => {
  const map = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

// 获取审核状态文本
const getAuditStatusText = (status) => {
  const map = {
    pending: '审核中',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return map[status] || status
}

// 获取审核步骤
const getAuditStep = (status) => {
  const map = {
    pending: 1,
    approved: 4,
    rejected: 4
  }
  return map[status] || 0
}

// 获取审核记录类型
const getAuditRecordType = (status) => {
  const map = {
    success: 'success',
    warning: 'warning',
    error: 'danger'
  }
  return map[status] || 'info'
}

// 获取通知类型文本
const getNotificationTypeText = (type) => {
  const map = {
    order: '订单通知',
    system: '系统通知',
    marketing: '营销通知'
  }
  return map[type] || type
}

onMounted(() => {
  getAccountDetail()
  getStatistics()
  getLoginHistory()
  getAuditHistory()
  getNotificationSettings()
})
</script>

<style lang="scss" scoped>
.merchant-account-detail {
  padding: 20px;

  .basic-form {
    max-width: 600px;
  }

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-value {
      font-size: 24px;
      font-weight: bold;
      margin: 10px 0;
    }

    .card-trend {
      font-size: 14px;
      color: #666;

      .up {
        color: #67c23a;
      }

      .down {
        color: #f56c6c;
      }
    }
  }

  .statistics-charts {
    .chart-container {
      height: 400px;
    }
  }

  .security-card {
    margin-bottom: 20px;

    .security-items {
      .security-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .item-info {
          .item-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
          }

          .item-desc {
            font-size: 14px;
            color: #666;
          }
        }
      }
    }
  }

  .audit-card {
    margin-bottom: 20px;
  }

  .notification-card {
    margin-bottom: 20px;

    .notification-content {
      white-space: pre-wrap;
      word-break: break-all;
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 